package com.chaihu.core.base.service.front;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chaihu.bean.enums.MsgCode;
import com.chaihu.bean.result.ResponseResult;
import com.chaihu.core.context.IPageData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

/**
 * @author chaihu
 * @date 2021/10/20
 */
@Slf4j
public abstract class AbstractComponentService extends BaseComponentService {
    /**
     * 统一业务处理类
     *
     * @param pd 页面数据封装
     * @return ResponseEntity对象
     */
    protected final ResponseEntity<String> businessProcess(IPageData pd) {

        JSONObject paramIn = JSONObject.parseObject(pd.getReqData());

        log.debug("businessProcess: pd=" + JSONObject.toJSONString(pd));


        //业务数据校验
        validate(pd, paramIn);
        ResponseEntity<String> responseEntity = null;
        try {
            responseEntity = doBusinessProcess(pd, paramIn);
        } catch (Exception e) {
            log.error("调用实现类异常：", e);
            ResponseResult result = new ResponseResult(MsgCode.ERROR.getCode(), e.getLocalizedMessage());
            responseEntity = new ResponseEntity<String>(JSON.toJSONString(result), HttpStatus.OK);
        }

        return responseEntity;

    }

    /**
     * 页面数据校验 方法
     *
     * @param pd      页面数据封装
     * @param paramIn 前台数据对象
     */
    protected abstract void validate(IPageData pd, JSONObject paramIn);

    /**
     * 业务数据处理类
     *
     * @param pd      页面数据封装
     * @param paramIn 前台数据对象
     */
    protected abstract ResponseEntity<String> doBusinessProcess(IPageData pd, JSONObject paramIn) throws Exception;
}
